<?php


namespace app\controller\admin\school;


use app\common\exception\ApiException;
use app\controller\admin\BaseAdminController;
use app\model\coach\UserCoachModel;
use app\model\goods\OrderModel;
use app\model\school\SchoolOrderModel;
use app\model\user\UserModel;
use app\service\order\SchoolOrderService;
use think\facade\Db;

class SchoolOrderController extends BaseAdminController
{

    function setModel()
    {
        return new SchoolOrderModel();
    }

    function setWithModel()
    {
        return ['school', 'source', 'coach'];
    }

    function setSearch()
    {
        $where = [];
        $where[] = ['status', '>', 1];
        return [
            '=' => ['city_id','mobile', 'order_type'],
            'like' => ['order_sn'],
            'betweenTimestamp' => ['create_time'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function save()
    {
        try {
            $id = $this->request->param('id', 0);
            $data = $this->request->only(['school_id', 'city_id', 'source_id', 'type', 'mobile', 'username', 'remark', 'course_name'], 'param', 'trim');
            if (!isset($data['city_id']) || !$data['city_id']) {
                throw new ApiException('请选择城市');
            }
            if (!isset($data['school_id']) || !$data['school_id']) {
                throw new ApiException('请选择驾校');
            }
            if (!isset($data['mobile']) || !$data['mobile']) {
                throw new ApiException('请填写用户手机号');
            }
            if (!isset($data['type']) || !$data['type']) {
                throw new ApiException('请选择类型');
            }
            if (!isset($data['course_name']) || !$data['course_name']) {
                throw new ApiException('请填写课程名');
            }

            $userId = UserModel::where('mobile', $data['mobile'])->value('id', 0);
            if (!$userId) {
                $userModel = new UserModel();
                $userModel->mobile = $data['mobile'];
                $userModel->username = $data['username'];
                $userModel->city_id = $data['city_id'];
                $userModel->save();
                $userId = $userModel->id;
            }
            $data['user_id'] = $userId;

            if (!$id) {
                $data['order_sn'] = createOrderSn('school_order', 'order_sn', 'XC');

                // 订单中心
                $orderModel = new OrderModel();
                $orderModel->order_sn = $data['order_sn'];
                $orderModel->order_type = 2;
                $orderModel->user_id = $data['user_id'];
                $orderModel->city_id = $data['city_id'];
                $orderModel->mobile = $data['mobile'];
                $orderModel->save();


                // 预约订单
                $data['status'] = 2;
                $coachId = UserCoachModel::where('school_id', $data['school_id'])
                    ->where('is_team_leader', 1)
                    ->value('id');
                if (!$coachId) {
                    throw new ApiException('驾校教练不存在');
                }
                $data['accept_uid'] = $coachId;
                $data['coach_id'] = $coachId;
                $this->setModel()->save($data);
            } else {
                $partnerOrderModel = $this->setModel()->find($id);
                $partnerOrderModel->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 上传券码
     * @return \think\response\Json
     */
    public function uploadCouponCode()
    {
        try {
            $id = $this->request->param('id', 0);
            $code = $this->request->param('code', '', 'trim');
            $img = $this->request->param('img', '', 'trim');

            $orderInfo = SchoolOrderModel::find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }

            $orderInfo->coupon_code = $code;
            $orderInfo->coupon_code_img = $img;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function complete()
    {
        try {
            $id = $this->request->param('id', 0);
            $amount = $this->request->param('amount', 0);

            $orderInfo = SchoolOrderModel::find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $orderInfo->coach_amount = $amount;
            $orderInfo->save();

            $schoolOrderService = new SchoolOrderService();
            $schoolOrderService->completeOrderService($id);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function del()
    {
        try {
            $id = $this->request->param('id', 0);

            $orderInfo = SchoolOrderModel::find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $orderInfo->delete();

            $orderCenter = OrderModel::where('order_sn', $orderInfo['order_sn'])->find();
            if ($orderCenter) {
                $orderCenter->order_status = -1;
                $orderCenter->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 添加跟踪记录
     * @return \think\response\Json
     */
    public function addRecord()
    {
        try {
            $id = $this->request->param('id', '');
            $remark = $this->request->param('remark', '');
            Db::name('school_order_log')->insert(['remark' => $remark, 'order_id' => $id, 'create_time' => time()]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 跟踪记录
     * @return \think\response\Json
     */
    public function getRecordList()
    {
        try {
            $id = $this->request->param('id', '');

            $list = Db::name('school_order_log')
                ->where('order_id', $id)
                ->order('id', 'desc')
                ->paginate(['list_row' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}